#include "udp.h"
// #include "IICline.h"

AsyncUDP udp;                     //创建UDP对象
IPAddress remote_IP(192, 168, 43, 184);// 自定义远程监 IP 地址
char udp_buf[15],buff[15];
int udp_int = 10;
int zero_num = 0;
int length_nm;
bool wifi_is_open = 0;
int wifi_start_time ;
unsigned int broadcastPort = remoteUdpPort;
uint8_t Q1[]="A" ;
char length_char[10]; 

void onPacketCallBack(AsyncUDPPacket packet)
{
  byte a[10] = {1};
  udp_int = packet.peek();
  sprintf(buff,"%d",packet.peek());
  udp_send(buff);
    if (packet.peek()==1) //绿灯
  {
    udp_send("zero");
    zero_num = received_length_Data;
    // Serial.println("copy it");
    // Serial.println("copy it");    
  }
  broadcastPort = packet.remotePort();
}

void udp_init()
{
  Serial0.println();
	WiFi.mode(WIFI_STA);

  WiFi.begin(ssid1, password1); //连接网络

  while (WiFi.status() != WL_CONNECTED  && (millis() - wifi_start_time < 6000)  ) //等待网络连接成功
  {
    delay(200);
    Serial0.print(".");
    if (WiFi.isConnected() == 1)
    {
      wifi_is_open = 1;
    }
    else
    {
      wifi_is_open = 0 ;
      // WiFi.disconnect();
    }
  }
  if (wifi_is_open){
  Serial0.println("WiFi connected!");
  Serial0.print("IP address: ");
  Serial0.println(WiFi.localIP()); //打印模块IP

  Serial0.print("subnetMask: ");
  Serial0.println(WiFi.subnetMask()); //打印子网掩码

  Serial0.print("gateway: ");
  Serial0.println(WiFi.gatewayIP()); //打印网关地址

  Serial0.print("dns: ");
  Serial0.println(WiFi.dnsIP()); //打印DNS地址

  Serial0.print("mac Address: ");
  Serial0.println(WiFi.macAddress()); //打印mac地址

  WiFi.setHostname("Tizami"); //设置主机名
  Serial0.print("HostName: ");
  Serial0.println(WiFi.getHostname()); //打印主机名
    // Udp.begin(localUdpPort); //启用UDP监听以接收数据
  wifi_start_time = millis();
  // wifi_wait_time
  while ((!WiFi.isConnected()) )
  {
    delay(200);
    Serial0.print(".");

  }


  Serial0.println("Connected");
  Serial0.print("IP Address:");
  Serial0.println(WiFi.localIP());
  
  while (!udp.listen(localUdpPort)) //等待udp监听设置成功
  {
		Serial0.print(".");
		delay(500); 
  }
  udp.onPacket(onPacketCallBack); //注册收到数据包事件
  ArduinoOTA.setHostname("ESP_CAR");
  ArduinoOTA.begin();
  Serial0.println("OTA ready");
  xTaskCreate(Monitor_Task, "Monitor", 2048, NULL, 1, NULL);//freeRTOS

  }
  else
  {
    WiFi.disconnect();
  }

}

 

void udp_send(char send_date[])
{
  udp.broadcastTo(send_date,broadcastPort); //可以使用该方法广播信息
}


void Monitor_Task(void* pvParameters)
{
  while (1)
  {
    length_nm = (received_length_Data-zero_num)*20/1.024;
    sprintf(length_char,"%d",length_nm);  
    // udp_send(length_char);
    ArduinoOTA.handle();
    vTaskDelay(10 / portTICK_PERIOD_MS);
  }
    
}


